<template>
  <div class="container">
    <div class="text">试题录入</div>
    <el-form :model="addList" :rules="listRules" ref="listRulesRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="学科:" prop="subjectID">
        <el-select placeholder="请选择" v-model="addList.subjectID" @change="getDirectory">
          <el-option v-for="(item, index) in sublist" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录:" prop="catalogID">
        <el-select placeholder="请选择" v-model="addList.catalogID">
          <el-option v-for="(item, index) in DirectoryLIst" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业:" prop="enterprise">
        <el-select placeholder="请选择" v-model="addList.enterpriseID">
          <el-option v-for="(item, index) in Enterprise" :value="item.id" :label="item.shortName" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市:" prop="province">
        <el-select placeholder="请选择" v-model="addList.province" class="city" @change="changeCity">
          <el-option v-for="(item, index) in provinces" :lable="item" :key="index" :value="item"></el-option>
        </el-select>
        <el-select placeholder="请选择" v-model="addList.city" class="city">
          <el-option v-for="(item, index) in citys" :lable="item" :key="index" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="方向:" prop="direction">
        <el-select placeholder="请选择" v-model="addList.direction">
          <el-option v-for="(item, index) in direction" :lable="item" :key="index" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型:" prop="questionType">
        <el-radio-group v-model="addList.questionType" @change="ChangeRadio">
          <el-radio :label="'1'">单选</el-radio>
          <el-radio :label="'2'">多选</el-radio>
          <el-radio :label="'3'">简答</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="难度:" prop="difficulty">
        <el-radio-group v-model="addList.difficulty">
          <el-radio v-for="(item, index) in difficulty" :key="index" :label="index + ''" :value="item">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题干:" prop="question">
        <quill-editor v-model="addList.question" :options="editorOption"> </quill-editor>
      </el-form-item>
      <template v-if="addList.questionType === '1'">
        <el-form-item label="选项: " v-model="codeNumberJ">
          <div v-for="(item, index) in addList.options" :key="index">
            <el-radio-group v-model="codeNumberJ">
              <el-radio :label="index">{{ item.code }}:</el-radio>
            </el-radio-group>
            <el-input class="itemClass" v-model="addList.options[index].title"></el-input>
            <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <i class="el-icon-circle-close"></i>
              <span>上传图片</span> </el-upload
            ><br />
          </div>
          <el-button type="danger" size="small" icon="el-icon-plus" :disabled="addDisabled">新增选项与答案</el-button>
        </el-form-item>
      </template>
      <template v-else-if="addList.questionType === '2'">
        <el-form-item label="选项: ">
          <div v-for="(item, index) in addList.options" :key="index">
            <!-- <el-radio-group v-model="codeNumberO">
              <el-radio :label="index">{{ item.code }}:</el-radio>
            </el-radio-group> -->
            <el-checkbox-group v-model="codeNumberO" class="itemGroup">
              <el-checkbox :label="index">{{ item.code }} :</el-checkbox>
            </el-checkbox-group>
            <el-input class="itemClass" v-model="addList.options[index].title"></el-input>
            <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
              <i class="el-icon-circle-close"></i>
              <span>上传图片</span> </el-upload
            ><br />
          </div>
          <el-button type="danger" size="small" icon="el-icon-plus" :disabled="addDisabled" @click="addCheckBox">新增选项与答案</el-button>
        </el-form-item>
      </template>
      <template v-else></template>

      <el-form-item label="解析视频:">
        <el-input class="remarks" v-model="addList.videoURL"></el-input>
      </el-form-item>
      <el-form-item label="答案解析:" prop="answer">
        <quill-editor v-model="addList.answer" :options="editorOption"> </quill-editor>
      </el-form-item>
      <el-form-item label="题目备注:">
        <el-input type="textarea" class="remarks" v-model="addList.remarks"></el-input>
      </el-form-item>
      <el-form-item label="试题标签:" prop="tags">
        <el-select v-model="addList.tags" multiple filterable allow-create default-first-option placeholder="请选择试题标签"> </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">确认提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 获取目录接口
import { simple as DirectoryList } from '@/api/hmmm/directorys'
// 获取企业的接口
import { list } from '@/api/hmmm/companys'
// difficulty, questionType,
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
import { simple } from '@/api/hmmm/subjects.js'
import { add, detail } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
export default {
  data () {
    return {
      addList: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '', // 企业
        direction: '', // 方向
        // 题型
        questionType: '1',
        difficulty: 1 + '', // 难度
        question: '', // 题干
        tags: [], // 试题标签
        remarks: '', // 题目备注
        answer: '', // 答案解析
        videoURL: '', // 解析视频,
        province: '',
        city: '',
        options: [ // 选项
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      tage: [], // 保存试题标签
      // 题型
      questionType,
      // 难度
      difficulty,
      // 方向
      direction,
      Enterprise: [], // 企业
      provinces: [], // 城市
      citys: [], // 区县
      // 获取学科
      sublist: [],
      // 目录列表
      DirectoryLIst: [],
      imageUrl: '',
      // 校验规则
      listRules: {
        subjectID: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请输入方向名称', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择题型难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请填写题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ]
      },
      codeNumberJ: null, // 单选选项双向数据绑定,记录是哪一个选项被选中的
      codeNumberO: [], // 多选选项，记录在多选情况下，被选中的选项
      // 自定义富文本编辑器
      editorOption: {
        placeholder: '编辑文章内容',
        modules: {
          toolbar: [
            // 加粗 斜体 下划线 删除线
            ['bold', 'italic', 'underline', 'strike'],
            // 有序列表 无序列表
            [{ list: 'ordered' }, { list: 'bullet' }],
            // 引用 代码块 图片 链接
            ['blockquote', 'code-block', 'image', 'link']
          ]
        }
      }
    }
  },
  props: ['id'],
  created () {
    this.getAddList()
    this.getProvinces()
    this.getEnterprise()
    this.getSetLIst()
  },
  methods: {
    async getSetLIst () { // 拿着动态路由传过来的值，获取数据
      if (this.$route.query.id) { // 判断当前动态路由是否传参
        const { data } = await detail({ id: this.$route.query.id })
        this.addList = data
        if (this.addList.questionType === '1') {
          this.addList.options.forEach((i, m) => {
            // eslint-disable-next-line no-return-assign
            if (i.isRight === 1) return this.codeNumberJ = m
          })
        } else if (this.addList.questionType === '2') {
          this.addList.options.forEach((i, m) => {
            if (i.isRight === 1) return this.codeNumberO.push(m)
          })
        }
        this.addList.tags = this.addList.tags.split(',')
        this.addList.catalogID = this.DirectoryLIst[this.addList.catalogID] ? this.DirectoryLIst[this.addList.catalogID] : ''
        this.addList.enterpriseID = this.Enterprise[this.addList.enterpriseID]
      }
    },
    async getAddList () {
      // 获取学科
      const { data } = await simple()
      console.log(data)
      // this.list = data
      this.sublist = data
      // console.log(this.list)
    },
    // 获取省市
    getProvinces () {
      this.provinces = provinces()
    },
    changeCity () { // 获取区县
      this.citys = citys(this.addList.province)
    },
    // 获取目录
    async getDirectory () {
      const { data } = await DirectoryList({ subjectID: this.addList.subjectID })
      this.DirectoryLIst = data
    },
    // 获取企业
    async getEnterprise () {
      const { data } = await list()
      this.Enterprise = data.items
    },
    addCheckBox () { // 点击新增选项卡，利用ascllc码
      const w = String.fromCharCode(65 + this.addList.options.length) // 根据当前的数组长度，生成asclls
      this.addList.options.push({ isRight: false, code: w, title: '', img: '' }) // 添加进数组中
    },
    ChangeRadio () {
      // 解决BUG：改变题型的时候，重置下方对应选项卡的双向数据绑定源
      this.addList.options = [ // 选项
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ]
      this.checkBoxList = ['A', 'B', 'C', 'D']
      this.addCheckBoxNumber = 0
    },
    submitForm () { // 添加！
      this.$refs.listRulesRef.validate(bel => {
        if (bel) {
          this.addList.tags = this.addList.tags.join(',') // 将标签数组转化
          if (this.addList.questionType === '1') { // 发送前将被彀中的选项转化为布尔值
            this.addList.options.forEach((i, m) => {
              if (m === this.codeNumberJ) {
                // eslint-disable-next-line no-return-assign
                return i.isRight = m
              }
            })
          } else if (this.addList.questionType === '2') {
            this.codeNumberO.forEach(i => {
              this.addList.options[i].isRight = true
            })
          }
          add(this.addList)
            .then(_ => {
              this.$message({ type: 'success', message: '录入成功!' })
              this.$router.push('/questions/list') // 成功后跳转
            })
            .catch(e => {
              console.log(e)
            })
        } else {
          return false
        }
      })
    },
    handleAvatarSuccess () { },
    beforeAvatarUpload () { }
  },
  watch: {
    codeNumber (val) { // 保持单选情况下选项标签只能被选中一个
      if (this.addList.questionType === '1') {
        this.addList.options.forEach((i, m) => {
          if (m === val) {
            i.isRight = true
          } else {
            i.isRight = false
          }
        })
      }
    }
  },
  computed: {
    addDisabled () { // 控制新增试题红色按钮高亮
      if (this.addList.questionType === '2') {
        return false// 选择多选才可以高亮
      } else {
        return true
      }
    }
  }
}
</script>
<style scoped lang='scss' rel="stylesheet/scss">
.container {
  margin: 15px 10px;
  // padding: 20px;
  background: #fff;
  .text {
    padding: 20px;
    margin-bottom: 30px;
    border-bottom: 1px solid #ebeef5;
  }
  .el-form {
    padding-left: 55px;
  }
  .el-select,
  .remarks {
    width: 400px;
    box-sizing: border-box;
  }
  .quill-editor {
    height: 200px;
    margin-bottom: 50px;
    margin-right: 20px;
  }
  .el-button {
    margin-bottom: 30px;
  }
  .itemClass {
    width: 250px;
    margin-bottom: 45px;
    margin-right: 25px;
    margin-left: 5px;
  }
  .itemGroup {
    width: 45px;
    display: inline-block;
  }
  .city {
    width: 200px;
    box-sizing: border-box;
    &:first-child {
      padding-right: 5px;
      //
    }
  }
  ::v-deep .avatar-uploader {
    display: inline-block;
    vertical-align: middle;
    line-height: 1;
    margin-left: 4px;
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      width: 100px;
      height: 60px;
      line-height: 60px;
    }
    .el-icon-circle-close {
      position: absolute;
      right: 0;
      top: 0;
      -webkit-transform: translate(50%, -50%);
      transform: translate(50%, -50%);
      background: #fff;
      font-size: 18px;
      color: #999;
    }
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
}
</style>
